<template>
	<view class="box">
		<image src="https://bzhl-dev1.oss-cn-chengdu.aliyuncs.com/bzhl/miniapp/yst/logo.png" mode="" class="logo">
		</image>
		<u-tabs :list="tablist" @click="tabClick"></u-tabs>
		<view class="formBox">
			<!-- 验证码登录 -->
			<view v-if="type == '0'">
				<u--form labelPosition="left" :model="formModel" :rules="rules" ref="uForm">
					<u-form-item label="登录账号" labelWidth="100" prop="phone" borderBottom ref="item1">
						<u--input v-model="formModel.phone" border="none" placeholder="请输入手机号"></u--input>
					</u-form-item>
					<u-form-item prop="smsVerificationCode" borderBottom>
						<u-input placeholder="请输入验证码" border="none" v-model="formModel.smsVerificationCode">
							<template slot="suffix">
								<u-code ref="uCode" @change="codeChange" startText="获取验证码" changeText="X秒重新获取"
									endText="重新获取验证码"></u-code>
								<u-button @tap="getCode" :text="tips" type="text" size="mini"
									:seconds="seconds"></u-button>
							</template>
						</u-input>
					</u-form-item>
					<!-- <u-form-item label="验证码" labelWidth="100" prop="code" borderBottom ref="item1">
						<view class="flex alignC">
							<u--input v-model="formModel.code" border="none"></u--input>
							<view @click="getUuid">
								<image :src="uuidImg" mode="" style="width: 140rpx;height: 65rpx;"></image>
							</view>
						</view>
					</u-form-item> -->
				</u--form>
			</view>
			<!-- 密码登录 -->
			<view v-else>
				<u--form labelPosition="left" :model="userInfo" :rules="rules" ref="uForm">
					<u-form-item label="登录账号" labelWidth="100" prop="username" borderBottom ref="item1">
						<u--input v-model="userInfo.username" border="none" placeholder="请输入账号"></u--input>
					</u-form-item>
					<u-form-item label="登录密码" labelWidth="100" prop="password" borderBottom ref="item1">
						<view class="flex">
							<u--input v-model="userInfo.password" border="none" placeholder="密码为6-16位字母和数字"
								:type="isShowPassword?'password':'text'"></u--input>
							<u-icon :name="isShowPassword? 'eye-off' : 'eye'" @click="togglePassShow"></u-icon>
						</view>
					</u-form-item>
					<!-- <u-form-item label="验证码" labelWidth="100" prop="code" borderBottom ref="item1">
						<view class="flex alignC">
							<u--input v-model="userInfo.code" border="none"></u--input>
							<view @click="getUuid">
								<image :src="uuidImg" mode="" style="width: 140rpx;height: 65rpx;"></image>
							</view>
						</view>
					</u-form-item> -->
				</u--form>
			</view>

			<view class="botText flex">
				<text style="color: #ccc;">没有账号？</text> <text @click="goRegister">去注册</text>
			</view>
			<view class="flex" style="justify-content: center;margin-top: 200rpx;" @click="youkeLogin">
				<view style="font-size: 36rpx;">游客登录</view>
			</view>
		</view>

		<view class="bottom">
			<view style="margin-bottom: 20rpx;">
				<u-checkbox-group>
					<u-checkbox v-model="checked" shape="circle" @change="checkboxChange">
					</u-checkbox>
					<view class="" style="color: #ccc;font-size: 24rpx;">
						我已阅读并同意<text class="link" @click="toPage(`/pagesA/commonPage/index?type=5`)">《用户协议》</text>
						和<text class="link" @click="toPage(`/pagesA/commonPage/index?type=6`)">《隐私政策》</text>
					</view>
				</u-checkbox-group>
			</view>
			<u-button text="登录" color="#00B4C7" @click="login"></u-button>
		</view>
	</view>
</template>

<script>
	import {
		$http
	} from '@/utils/index.js'
	import {
		mapMutations
	} from 'vuex'
	import {
		sendSms,
		createCaptcha,
		getUserApi,
		getPhoneApi
	} from '../../common/API/loginOrregister.js'
	export default {
		data() {
			return {
				isShowPassword: true,
				// 手机号
				formModel: {
					code: '',
					key: 'yst',
					phone: '',
					smsVerificationCode: '',
					uuid: ''
				},
				// 账号密码
				userInfo: {
					key: 'yst',
					password: '',
					username: '',
					code: '',
					uuid: ''
				},
				tablist: [{
						name: '密码登录',
						type: '1'
					},
					{
						name: '验证码登录',
						type: '0'
					},
				],
				type: '1',
				rules: {
					// 字段名称
					phone: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// uni.$u.test.mobile()就是返回true或者false的
								console.log(value, uni.$u.test.mobile(value))
								return uni.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}
					],
					verificationCode: {
						type: 'string',
						required: true,
						len: 4,
						message: '请填写4位验证码',
						trigger: ['blur']
					},
				},
				checked: false, //同意条款
				seconds: 60,
				tips: '',
				uuid: '',
				uuidImg: '',
				openId: '',
				appId: "wxda2ecdb815e2e98f",
				sessionKey: ''
			}
		},
		onload() {},
		async onShow() {
			this.getUuid()
			this.getPhone()
		},
		methods: {
			...mapMutations('user', ['MusetToken', 'MusetUserInfo']),
			togglePassShow(index) {
				this.isShowPassword = !this.isShowPassword
			},
			async getPhone() {
				const r = await getPhoneApi()
				// console.log("获取",r)
				this.openId = r.data.openId
			},
			// 获取uuid
			async getUuid() {
				const res = await createCaptcha()
				if (res.status == 200) {
					this.uuid = res.data.uuid
					this.uuidImg = `data:image/png;base64,${res.data.img}`
					// this.formModel.uuid = this.uuid
					// this.userInfo.uuid = this.uuid
				}
			},
			tabClick(item) {
				console.log('item', item);
				this.type = item.type
			},
			codeChange(text) {
				this.tips = text;
			},
			checkboxChange(val) {
				// console.log('change', n);
				this.checked = val
			},
			async getCode() {
				if (!this.formModel.phone) {
					uni.$u.toast('请先输入手机号');
					return;
				}
				if (this.$refs.uCode.canGetCode) {
					uni.showLoading({
						title: '正在获取验证码'
					})
					const res = await sendSms(this.formModel.phone)
					// console.log(res)
					if (res.status == 200) {
						uni.hideLoading();
						// 这里此提示会被this.start()方法中的提示覆盖
						uni.$u.toast('验证码已发送');
						// 通知验证码组件内部开始倒计时
						this.$refs.uCode.start();
					}
				} else {
					uni.$u.toast('倒计时结束后再发送');
				}
			},
			end() {
				uni.$u.toast('倒计时结束');
			},
			start() {
				uni.$u.toast('倒计时开始');
			},
			goRegister() {
				uni.navigateTo({
					url: '/pages/register/register'
				})
			},
			// 游客登录，获取openid
			youkeLogin() {
				let that = this
				if (!that.checked) {
					uni.$u.toast('请同意勾选用户协议及隐私协议')
					return;
				}
				let data = {
					source: '5',
					touristLoginReqDto: {
						key: 'yst',
						openid: this.openid,
					}
				}
				uni.request({
					url: `${$http.baseUrl}/api/auth/finalLogin`, //请求路径
					data: JSON.stringify(data),
					method: "POST", //请求方式
					header: { //请求头配置
						'Content-Type': 'application/json', //设置请求类型，到接口文档中找
					},
					success: (res) => { //请求成功后的回调
						let data = res.data
						uni.$u.toast(data.message)
						if (data.status == 200) {
							// 登录成功
							console.log('游客登录成功', data)
							that.MusetToken({
								accessToken: data.data
									.accessToken,
								phone: data.phoneNumber,
								role: 0 // 身份0老板1医生2会员
							})
							// console.log('缓存token成功')
							// 缓存用户信息
							getUserApi().then((res) => {
								console.log(res)
								// console.log('用户信息', JSON.stringify(res))
								that.MusetUserInfo(res
									.data)
								uni.switchTab({
									url: "/pages/home/home"
								})
							})
						}
					},
					fail: (err) => { //请求失败后的回调
						uni.showToast({
							icon: "error",
							title: err,
							duration: 1000
						})
					}
				})
			},
			login() {
				let data;
				// 手机号验证码登录
				let params1 = {
					phoneVerificationCodeReqDto: this.formModel,
					source: '3'
				}
				// 账号密码登录
				let params2 = {
					loginUserReqDto: this.userInfo,
					source: '4'
				}
				data = this.type == '0' ? params1 : params2
				if (data && !this.checked) {
					uni.$u.toast('请同意勾选用户协议及隐私协议')
					return;
				}
				console.log("登录", data)
				uni.request({
					url: `${$http.baseUrl}/api/auth/finalLogin`, //请求路径
					data: JSON.stringify(data),
					method: "POST", //请求方式
					header: { //请求头配置
						'Content-Type': 'application/json', //设置请求类型，到接口文档中找
					},
					success: (res) => { //请求成功后的回调
						let data = res.data
						uni.$u.toast(data.message)
						if (data.status == 200) {
							// 登录成功
							console.log('登录成功', data)
							this.MusetToken({
								accessToken: data.data.accessToken,
								phone: data.phoneNumber,
								role: 0 // 身份0老板1医生2会员
							})
							console.log('缓存token成功')
							// 缓存用户信息
							getUserApi().then((res) => {
								console.log(res)
								console.log('用户信息', JSON.stringify(res))
								this.MusetUserInfo(res.data)
								uni.switchTab({
									url: "/pages/home/home"
								})
							})

							// let data1 = this.getuserInfo()
							// this.MusetUserInfo(data1)
							// uni.switchTab({
							// 	url:"/pages/home/home"
							// })
						}
					},
					fail: (err) => { //请求失败后的回调
						uni.showToast({
							icon: "error",
							title: err,
							duration: 1000
						})
					}
				})

				// }).catch(errors => {
				// 	uni.$u.toast('校验失败')
				// })
			}
		}
	}
</script>

<style lang="scss" scoped>
	.box {
		width: 80%;
		margin: 220rpx auto;
		position: relative;
		height: calc(100vh - 220rpx);

		.logo {
			width: 276rpx;
			height: 80rpx;
			margin-bottom: 50rpx;
		}

		.formBox {
			margin-top: 50rpx;
			font-size: 24rpx !important;

			.botText {
				margin-top: 20rpx;
				justify-content: flex-end;
				font-size: 24rpx;
			}

			/deep/.u-button__text {
				color: #00B4C7 !important;
				font-size: 24rpx !important;
			}
		}

		.bottom {
			width: 100%;
			position: absolute;
			bottom: 100rpx;

			.link {
				color: #00B4C7;
			}
		}
	}
</style>